package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"hello/database"
	"hello/models"
	"hello/utils"
	"net/http"
)

func handleValidationError(ctx *gin.Context, err error) {
	errors := make(map[string]string)
	for _, err := range err.(validator.ValidationErrors) {
		errors[err.Field()] = err.Tag()
	}

	ctx.JSON(http.StatusBadRequest, utils.JSONResult{
		Code:    http.StatusBadRequest,
		Message: "参数错误",
		Data:    errors,
	})
}

func CreatePackage(ctx *gin.Context) {
	var updatePackageDto models.UpdatePackageDTO

	if err := ctx.ShouldBind(&updatePackageDto); err != nil {
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	if err := updatePackageDto.Validate(); err != nil {
		handleValidationError(ctx, err)
	}

	packageD := &models.Package{
		MerchantId: updatePackageDto.MerchantId,
		PackageNo:  updatePackageDto.PackageNo,
		StorageId:  updatePackageDto.StorageId,
		Status:     updatePackageDto.Status,
	}

	if err := database.DB.Create(packageD).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, utils.JSONResult{
			Code:    http.StatusInternalServerError,
			Message: "创建失败",
			Data:    err,
		})
		return
	}

	ctx.JSON(http.StatusCreated, utils.JSONResult{
		Code:    http.StatusCreated,
		Message: "创建成功",
		Data:    packageD,
	})
}

func ListPackage(ctx *gin.Context) {
	var packageList []models.Package
	// 使用 Find 而不是 First 来获取所有记录
	if err := database.DB.Preload("Storage").Find(&packageList).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, utils.JSONResult{
			Code:    http.StatusInternalServerError,
			Message: "查询错误",
			Data:    err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, utils.JSONResult{
		Code:    http.StatusOK,
		Message: "查询成功",
		Data:    packageList,
	})
}
